const $api = require('../../utils/api').API.ask
const $cache = require('../../utils/storage')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    text: '',
    pics: [],
    openId:null,
    id:null,
    title:null
  },
  handleDel(e){
    let index = e.target.dataset.index
    let pics = this.data.pics
    pics.splice(index,1)
    this.setData({
      pics
    })
    console.log(1111111111,e)
  },
  getText(e) {
    let text = e.detail.value
    console.log(text)
    this.setData({
      text
    })
  },
  handleSend() {
    let params = {
      questionId:this.data.id,
      commenter:this.data.openId,
      content:this.data.text,
      parentId:0
    }
    $api.addAnswer(params).then(res => {
      let commentId = res.data.data
      let pics = this.data.pics
      let that = this
      if(res.data.code==200 && pics.length>0){
        for (let i = 0; i < pics.length; i++) {
          wx.uploadFile({
            url: `https://qdwlkj.cn/questioncomment/listCommentImgs?commentId=${commentId}`,
            filePath: pics[i],
            name: "imgs",
            header: {
              "content-type": "multipart/form-data"
            },
            success(res) {
              console.log(res,'图片上传')
              that.handleBack()
            },
            fail(err) {
              console.log(err,1);
            },
            complete(result) {
              console.log(result.errMsg,2)
            }
          })
        }
      }else{
        this.handleBack()
      }
    })
  },
  handleBack() {
    let {id,openId} = this.data
    wx.redirectTo({
      url: `/pages/ask_detail/ask_detail?id=${id}&openId=${openId}`,
    })  
  },
  handleAdd() {
    wx.chooseMedia({
      count: 9,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        console.log(res)
        let pics = res.tempFiles.map(item => item.tempFilePath)
        this.setData({
          pics: [...this.data.pics, ...pics]
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let {id,openId,title} = options
    this.setData({
      id,
      openId,
      title
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})